#!/usr/bin/env python3
# coding=utf-8
# @author Loganli
import os
import re
import json
import sys

"""
:: http://wuyou.run/monitor/zabbix/ports.discovery.py
python port_discover.py
"""

'''
Author: Logan.Li
Gitee: https://gitee.com/attacker
email: admin@attacker.club
Date: 2025-05-01 12:54:56
LastEditTime: 2025-05-01 13:02:31
Description: Zabbix端口自动发现脚本，排除高端口
'''
#!/usr/bin/env python3
# coding=utf-8
import os
import re
import json
import sys

def port_dict():
    # 黑名单：直接排除的端口或进程名
    drop_list = ['25', '111', 'zabbix_agent', 'zabbix_agentd', 'master', 'rpcbind', 'sshd']
    drop_str = "|".join(drop_list)
    
    # 获取所有监听端口和进程名
    cmd = """netstat -pntl | awk '/[0-9]\//{print $4,$7}' | sed 's/:$//' | sed 's_.*\:__' | sed 's#[ ][0-9].*/#:#g' | sort | uniq | egrep -vw '%s'""" % drop_str
    result_str = os.popen(cmd).read().splitlines()
    
    service_dict = {}
    for line in result_str:
        # 匹配格式如 "80:nginx" 或 "9000:docker-proxy"
        port_reg = re.search(r"(\d+):(\S+)", line)
        if port_reg:
            port, name = port_reg.groups()
            
            # [业务域] 排除10000-65535范围的高端口
            if int(port) < 10000:
                service_dict[port] = name
         
    
    return service_dict

def json_zabbix(args):
    ports = [{"{#PNAME}": name, "{#PPORT}": port} for port, name in args.items()]
    return json.dumps({"data": ports}, indent=4)

if __name__ == "__main__":
    local_ports = port_dict()
    print(json_zabbix(local_ports))